<template>
    <div/>
</template>

<script>
  import Cookies from 'js-cookie';

  const PASSPORT_DOMAIN = process.env.VUE_APP_PASSPORT_DOMAIN;
  const MAX_AGE = process.env.VUE_APP_REMEMBER_ME_MAX_AGE;
  export default {
    name: 'sso',
    data() {
      return {};
    },
    computed: {
      isTop() {
        return window.stop === window.self;
      },
    },
    created() {
      if (this.isTop) {
        window.close();
      }
    },
    mounted() {
      this.$nextTick(() => {
        if (!this.isTop) {
          window.addEventListener('message', (event) => {
            const { origin, data } = event;
            const { SIGN, AUTH_REMEMBER_ME, AUTH_TOKEN } = data;
            if (typeof SIGN === 'undefined') {
              return;
            }
            // 退出登录
            if (SIGN === 'logout') {
              Cookies.remove('AUTH_TOKEN');
              console.log('退出系统....');
              return;
            }
            if (PASSPORT_DOMAIN === origin && SIGN === 'login' && AUTH_TOKEN) {
              console.log('登录系统....');
              if (AUTH_REMEMBER_ME) {
                const expires = new Date(new Date().getTime() + MAX_AGE * 60 * 60 * 1000);
                Cookies.set('AUTH_TOKEN', AUTH_TOKEN, { expires });
              } else {
                Cookies.set('AUTH_TOKEN', AUTH_TOKEN);
              }
            }
          });
        }
      });
    },
  };
</script>
